package com.baizhi.realm;

import com.baizhi.entity.CmfzAdmin;
import com.baizhi.mapper.CmfzAdminMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
@Component
public class MyPermissionRealm extends AuthorizingRealm {
    private static final Logger logger = LoggerFactory.getLogger(MyPermissionRealm.class);
    @Autowired
    private CmfzAdminMapper cmfzAdminMapper;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("开始授权");
//        1.得到用户的账号
        String username = (String) principals.getPrimaryPrincipal();
//        2.查询改用户拥有的角色信息 和 资源权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(Arrays.asList("admin"));
        info.addStringPermissions(Arrays.asList("banner:add","banner:update"));
        logger.info("获取权限信息 封装在info中");
        return info;
    }

    /**
     * 认证相关代码
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info("调用了自己的realm"+this.getName());
//        1.token中有输入的账号密码  能够获取到账号  可以通过账号查数据库中的信息
        String username = (String) token.getPrincipal();

        logger.info("获取到用户输入的账号信息：{}",username);
//        2.模拟获取数据库数据  以后是调用dao

        QueryWrapper<CmfzAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        CmfzAdmin cmfzAdmin = cmfzAdminMapper.selectOne(wrapper);

        if(cmfzAdmin!=null){
//        3.把数据库查出来的账号密码封装在info中  三个参数：账号  密码  当前类的名字

            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(cmfzAdmin.getUsername(),cmfzAdmin.getPassword(),this.getName());
            logger.info("获取了info"+info.toString());
            return info;
        }
        logger.info("认证查询完成");
        return null;
    }
}
